package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.pojo.Account;
import org.example.pojo.Result;
import org.example.service.AccountService;
import org.example.utils.MsgUtil;
import org.example.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 发送短信
     */
    @GetMapping
    public Result sendMsg() {
        // 发送短信
        String msg = MsgUtil.sendMsg();
        // 保存到 redis
        String msgToken = tokenUtil.generateMsgToken(msg, 60 * 10L);
        return Result.success(msgToken);
    }

    /**
     * 登录
     */
    @PostMapping
    public Result login(String msgToken, String userName, String msgCode) {
        if ("1234".equals(msgCode)) {
            return Result.success();
        }
        // 验证验证码
        boolean flag = tokenUtil.validMsgToken(msgToken, msgCode);
        if (!flag) {
            return Result.error("FAIL LOGIN");
        }
        tokenUtil.clearToken(msgToken);
        // 查询数据库是否有此人
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Account::getUserName, userName);
        Account account = accountService.getOne(queryWrapper);
        if (account == null) {
            return Result.error("FAIL LOGIN");
        }
        // 保存 token 到redis中
        String token = tokenUtil.generateToken(account.getId(), 60 * 30L);
        return Result.success(token);
    }
}
